package com.digitaldreamers.framework.scene;

import org.andengine.entity.IEntity;
import org.andengine.entity.scene.Scene;

import com.digitaldreamers.framework.BaseResourceManager;

public abstract class ManagedScene extends Scene {
	protected final boolean mHasLoadingScene;
	protected final float mMinLoadingSceneTime;
	protected float mElapsedLoadingScreneTime;
	protected boolean mIsLoaded;
	protected BaseResourceManager mBaseResourceManager;
	
	public ManagedScene() {
		this(0f);
	}
	
	public ManagedScene(float minLoadingSceneTime) {
		this.mElapsedLoadingScreneTime = 0f;
		this.mIsLoaded = false;
		this.mMinLoadingSceneTime = minLoadingSceneTime;
		this.mHasLoadingScene = minLoadingSceneTime > 0f;
		this.mBaseResourceManager = BaseResourceManager.getInstance();
		this.setOnSceneTouchListenerBindingOnActionDownEnabled(true);
		this.setTouchAreaBindingOnActionDownEnabled(true);
		this.setTouchAreaBindingOnActionMoveEnabled(true);
	}
	
	public void onLoadManagedScene() {
		if(!this.mIsLoaded) {
			this.onLoadScene();
			this.mIsLoaded = true;
			this.setIgnoreUpdate(true);
		}
	}
	
	public void onUnloadManagedScene() {
		if(this.mIsLoaded) {
			this.mIsLoaded = false;
			this.mBaseResourceManager.mEngine.runOnUpdateThread(new Runnable() {
				@Override
				public void run() {
					ManagedScene.this.onUnloadScene();
				}
			});
		}
	}
	
	public void onShowManagedScene() {
		this.setIgnoreUpdate(false);
		this.onShowScene();
	}
	
	public void onHideManagedScene() {
		this.setIgnoreUpdate(true);
		this.onHideScene();
	}
	
	@Override
	public void attachChild(final IEntity entity) throws IllegalStateException {
		entity.setScale(this.mBaseResourceManager.mCameraScaleFactorX, this.mBaseResourceManager.mCameraScaleFactorY);
		super.attachChild(entity);
	}
	
	public abstract Scene onLoadingSceneLoadAndShown();
	public abstract void onLoadingSceneUnloadAndHidden();
	public abstract void onLoadScene();
	public abstract void onShowScene();
	public abstract void onHideScene();
	public abstract void onUnloadScene();
}